package hotnet.test;

import hotnet.buffer.IoBuffer;
import hotnet.filter.IoFilterAdapter;
import hotnet.filter.IoFilterChainBuilder;
import hotnet.future.CloseFuture;
import hotnet.future.ConnectFuture;
import hotnet.future.WriteFuture;
import hotnet.handler.IoHandlerAdapter;
import hotnet.nio.NioSocketConnector;
import hotnet.service.IoConnector;
import hotnet.session.IoSession;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class ClientAdapter extends IoFilterAdapter {
	private static Logger logger = LoggerFactory.getLogger(ClientAdapter.class);
	
	public ClientAdapter(String name) {
		super(name);
	}
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session,
			Object message) {
		if (message instanceof IoBuffer) {
			IoBuffer buffer = (IoBuffer)message;
			Charset charset = Charset.forName("UTF-8");
			CharsetDecoder decoder = charset.newDecoder();
			CharBuffer charBuffer = null;
			try {
				charBuffer = decoder.decode(buffer.buf().asReadOnlyBuffer());
			} catch (CharacterCodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String m = new String(charBuffer.toString());
			
			logger.info("filter:myiofilter" + m);
		}
		
		nextFilter.messageReceived(session, message);
	}
}

class ClientHandler extends IoHandlerAdapter {
    public void sessionCreated(IoSession session) {
        System.out.println("sessionCreated");
    }

    public void sessionOpened(IoSession session) {
    	System.out.println("sessionOpened");
    }
}

public class Client {
	public static void main(String[] args) {
		IoConnector connector = new NioSocketConnector();
		connector.setHandler(new ClientHandler());
		IoFilterChainBuilder clientChain = connector.getIoFilterChainBuilder();
		clientChain.addLast(new ClientAdapter("client"));

		try {
			SocketAddress address = new InetSocketAddress("127.0.0.1", 9090);
			ConnectFuture future = connector.connect(address);
			future.await();

			if (future.isConnected()) {
                System.out.println("9090 connect success");
            } else {
			  throw new IllegalStateException("cann't connect");
            }

			IoSession session = future.getSession();
			IoBuffer buffer = IoBuffer.wrap("connectok".getBytes());
			WriteFuture writeFuture = session.write(buffer);
			writeFuture.await();
			
			System.out.println("send msg 9090 success");
			
			CloseFuture future2 = session.close(false);
			future2.await();
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
